<template>
  <div class="main">
    <!-- 操作区 -->
    <div class="action">
      <el-button
          color="#909399"
          plain
          :icon="Search"
          @click="search"
          style="width: 75px;margin-left: 15px"
      >查询</el-button
      >

      <el-button
          color="#409eff"
          plain
          :icon="Plus"
          @click="add"
          style="margin-left: 10px"
      >新增</el-button
      >

      <el-button type="danger" plain :icon="Delete" @click="deleteAll"
      >批量删除</el-button
      >

      <el-button @click="toggleAllRows" plain :icon="Share">
        {{ isAllExpanded ? '折叠所有' : '展开所有' }}</el-button>
    </div>

    <!-- 数据展示区 -->
    <div class="data">
      <!-- 表格 -->
      <div class="grid">
        <el-table
            :data="tableData"
            style="width: 100%"
            :header-cell-style="headerCellStyle"
            @row-click="rowClick"
            :row-key="(row) => row.classificationId"
            ref="tableRef"
        >
          <el-table-column
              type="selection"
              width="50"
              align="center"
              header-align="center"
          />
          <el-table-column
              prop="classificationId"
              label="分类ID"
              width="100"
              align="center"
              header-align="center"
          />
          <el-table-column
              prop="classificationName"
              label="分类名"
              width="200"
              align="center"
              header-align="center"
          />
          <el-table-column
              prop="classificationDescription"
              label="分类描述"
              width="200"
              align="center"
              header-align="center"
          />
          <el-table-column
              prop="parentClassificationId"
              label="父类别"
              width="200"
              align="center"
              header-align="center"
          />
          <el-table-column
              prop="seq"
              label="序号"
              width="100"
              align="center"
              header-align="center"
          />

          <el-table-column fixed="right" label="操作" min-width="200">
            <template #default="scope">
              <el-button
                  color="#409eff"
                  :icon="Edit"
                  style="width: 70px"
                  @click="edit(scope.row)"
                  plain
              >编辑</el-button
              >
              <el-button
                  type="danger"
                  plain
                  :icon="Delete"
                  @click="removeById(scope.row)"
                  style="width: 70px"
              >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>

  <!-- 新增 对话框 -->
  <el-dialog
      v-model="show"
      :title="title"
      width="500"
      draggable
      :close-on-click-modal="false"
      @close="close"
  >
    <el-form ref="sfRef" :model="cfm">
      <el-form-item
          label="分类名:"
          label-width="100"
          prop="classificationName"
          style="width: 80%"
          :rules="[
          {
            required: true,
            message: '分类名',
            trigger: 'blur',
          },
        ]"
      >
        <el-input v-model="cfm.classificationName" />
      </el-form-item>
    </el-form>

    <el-form-item label="序号:" label-width="100" prop="seq" style="width: 80%">
      <el-input v-model="cfm.seq" />
    </el-form-item>

    <!-- 树形选择 -->
    <el-form-item
        label="父类别:"
        label-width="100"
        prop="parentClassificationId"
        style="width: 80%"
    >
      <el-tree-select
          v-model="cfm.parentClassificationId"
          :data="comboTreeData"
          :render-after-expand="false"
      />
    </el-form-item>

    <el-form-item label="分类描述:" label-width="100" prop="classificationDescription">
      <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入描述"
          v-model="cfm.classificationDescription"
          style="width: 75%"
      />
    </el-form-item>

    <!-- 对话框按钮，#插槽: 组件空出来，允许用户更改组件内容。由组件使用者定义 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submitForm"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import categoryApi from "@/api/CategoryApi";
import { reactive, ref } from "vue";
import { onMounted, toRaw, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Refresh,
  Plus,
} from "@element-plus/icons-vue";

const value2 = ref(true);

//当组件挂载结束之后调用
onMounted(() => {
  search();
  document.title = "植物表型数据管理系统";
});

//响应式对象
const tableData = ref([]);

// 当页码和页码大小改变时触发
function search() {
  categoryApi.findAll().then((result) => {
    if (result.code == 200) {
      console.log(result.data.children);
      tableData.value = result.data.children;
    }
  });
}
// 定义树
let comboTreeData = ref();
// 下拉数据
// // 表单实例的引用
let searchFromRef;
function resetSearch() {
  // 重置查询表单
  searchFromRef.resetFields();
}
// 定义表格实例
let tableRef;
//当点击表格时触发
function rowClick(row) {
  tableRef.toggleRowSelection(row);
}

// 删除操作逻辑
function deleteAll() {
  // 从表格中选中的行
  let rows = tableRef.getSelectionRows();
  let ids = []; //id数组
  for (let row of rows) {
    ids.push(row.classificationId);
  }
  console.log(ids);
  //执行删除操作
  deleteById(ids);
}
//根据id数组批量删除
function deleteById(ids) {
  console.log(ids);
  // 判断是否选中了要删除的记录
  if (ids.length == 0) {
    ElMessage({
      message: "请选中要删除的记录！",
      type: "warning",
    });
  } else {
    ElMessageBox.confirm("是否确定删除选中的记录吗？", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      categoryApi
          .removeAll(ids)
          .then((resp) => {
            console.log(resp);
            if (resp.code == 200) {
              ElMessage({
                type: "success",
                message: "操作成功，共删除" + resp.data + "行",
              });
              search(); //刷新
            } else {
              ElMessage({
                type: "error",
                message: resp.msg,
              });
            }
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "删除操作取消",
            });
          });
    });
  }
}
//  按id删除
function removeById(row) {
  let category = toRaw(row);
  deleteById([category.classificationId]);
}

// 对话框是否显示
const show = ref(false);

// 定义对话框内容
const categoryFormModel = ref({
  classificationName: "",
  classificationDescription: "",
  parentClassificationId: "",
  seq: ""
});
// 对话框内容别名
const cfm = categoryFormModel;

// 对话框标题
const title = ref("新增分类");
// 弹出新增
function add() {
  show.value = true;
  title.value = "新增分类";
  // 获取用户选中的行
  let rows = tableRef.getSelectionRows();
  console.log(rows);

  // 设置父级分类ID
  cfm.value.parentClassificationId = rows.length > 0
      ? toRaw(rows[0]).classificationId
      : "";

  // 下一个时间滴答中赋值
  nextTick(() => {
    cfm.value = {
      parentClassificationId: cfm.value.parentClassificationId // 保留父级ID
    }; //给新增/修改表单赋值
  });
}

// 查询下拉树
let result = categoryApi.findAll().then((res) => {
  if (res.code == 200) {
    let tree = res.data.children;
    buildCompoTree(tree); // 构建树
    comboTreeData.value = tree;
  }
});

function buildCompoTree(nodeArr) {
  for (let node of nodeArr) {
    node.label = node.classificationName;
    node.value = node.classificationId;
    if (Array.isArray(node.children)) {
      buildCompoTree(node.children);
    }
  }
}
// 提交表单
function submitForm() {
  let category = cfm.value;
  console.log(category);
  if (category.classificationId) {
    //修改
    submitEdit(category);
  } else {
    //新增
    submitAdd(category);
  }
}

// 新增逻辑
function submitAdd(category) {
  categoryApi.save(category).then((resp) => {
    console.log(resp);
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "新增成功",
      });
      search();
    }else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

let sfRef;
// 关闭对话框，重置表单
function close() {
  sfRef.resetFields();
  show.value = false;
  cfm.value = {};
}

// 修改操作
function edit(row) {
  let category = toRaw(row);
  // 浅拷贝
  row = Object.assign({}, category);
  show.value = true;
  title.value = "修改分类";
  // 下一个时间滴答中赋值
  nextTick(() => {
    cfm.value = row; //给新增/修改表单赋值
  });
}
// 提交表单执行逻辑
function submitEdit(category) {
  categoryApi.update(category).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: "修改失败",
      });
    }
  });
  show.value = false;
}

//表头样式
function headerCellStyle() {
  return {
    background: " #f4f4f5",
    textAlign: "center",
    color: "#909399",
  };
}

// 切换状态
function switchChange2(row) {
  let category = toRaw(row);
  categoryApi.updataByState(category).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
}

// 一键展开
const isAllExpanded = ref(false);

const toggleAllRows = () => {
  isAllExpanded.value = !isAllExpanded.value;
  toggleRowExpansion(tableData.value, isAllExpanded.value);
};

const toggleRowExpansion = (rows, expanded) => {
  rows.forEach(row => {
    if (row.children) {
      toggleRowExpansion(row.children, expanded);
    }
    tableRef.value.toggleRowExpansion(row, expanded);
  });
};
tableRef = ref(null);
</script>

<style scoped>
/* 定义不同状态下的 CSS 类 */
.el-switch-enabled {
  --el-switch-on-color: #13c75b;
  --el-switch-off-color: #13c75b;
}
.el-switch-disabled {
  --el-switch-on-color: #f56c6c;
  --el-switch-off-color: #f56c6c;
}
.pagination {
  margin-top: 20px;
}
.search {
  display: flex;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.search > form .el-form-item {
  flex-grow: 1;
  margin-right: 10px;
  margin-bottom: 0;
}
.action {
  margin-bottom: 5px;
  width: 100%;
  display: flex;
  padding: 10px 0;
  border-radius: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
}
.dialog-footer {
  margin-top: 20px;
}
.data {
  margin-top: 5px;
  padding: 15px 10px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
